package com.csp.mingyue.common.mybatis.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.csp.mingyue.common.core.constant.HttpStatus;
import com.csp.mingyue.common.core.exception.ServiceException;
import com.csp.mingyue.common.satoken.utils.LoginHelper;
import com.csp.mingyue.system.api.vo.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.util.ClassUtils;

import java.nio.charset.Charset;
import java.time.LocalDateTime;

/**
 * MP Create&Update 注入处理器
 *
 * @author njy
 * @date 2023/9/12 14:26
 */
@Slf4j
// @Component
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {

	@Override
	public void insertFill(MetaObject metaObject) {
		log.debug("mybatis plus start insert fill ....");
		LocalDateTime now = LocalDateTime.now();
		try {
			fillValIfNullByName("createTime", now, metaObject, false);
			fillValIfNullByName("updateTime", now, metaObject, false);
			fillValIfNullByName("createBy", getLoginUsername(), metaObject, false);
			fillValIfNullByName("updateBy", getLoginUsername(), metaObject, false);
		}
		catch (Exception e) {
			throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.UNAUTHORIZED);
		}
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		log.debug("mybatis plus start update fill ....");
		try {
			fillValIfNullByName("updateTime", LocalDateTime.now(), metaObject, true);
			fillValIfNullByName("updateBy", getLoginUsername(), metaObject, true);
		}
		catch (Exception e) {
			throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.UNAUTHORIZED);
		}
	}

	/**
	 * 填充值，先判断是否有手动设置，优先手动设置的值，例如：job必须手动设置
	 * @param fieldName 属性名
	 * @param fieldVal 属性值
	 * @param metaObject MetaObject
	 * @param isCover 是否覆盖原有值,避免更新操作手动入参
	 */
	private static void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject, boolean isCover) {
		// 1. 没有 set 方法
		if (!metaObject.hasSetter(fieldName)) {
			return;
		}
		// 2. 如果用户有手动设置的值
		Object userSetValue = metaObject.getValue(fieldName);
		String setValueStr = StrUtil.str(userSetValue, Charset.defaultCharset());
		if (StrUtil.isNotBlank(setValueStr) && !isCover) {
			return;
		}
		// 3. field 类型相同时设置
		Class<?> getterType = metaObject.getGetterType(fieldName);
		if (ClassUtils.isAssignableValue(getterType, fieldVal)) {
			metaObject.setValue(fieldName, fieldVal);
		}
	}

	/**
	 * 获取登录用户名
	 */
	private String getLoginUsername() {
		LoginUser loginUser;
		try {
			loginUser = LoginHelper.getLoginUser();
		}
		catch (Exception e) {
			log.warn("自动注入警告 => 用户未登录");
			return null;
		}
		return ObjectUtil.isNotNull(loginUser) ? loginUser.getUsername() : null;
	}

}
